<template>
  <div class="page-container">
    <a-card>
      <!-- 搜索表单 -->
      <a-card class="mb-4" style="background: var(--color-fill-1);">
        <a-form
          :model="searchForm"
          layout="inline"
          @submit="handleSearch"
        >
          <a-form-item label="角色名称">
            <a-input
              v-model="searchForm.roleName"
              placeholder="请输入角色名称"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="角色编码">
            <a-input
              v-model="searchForm.roleCode"
              placeholder="请输入角色编码"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="状态">
            <a-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              allow-clear
            >
              <a-option :value="1">启用</a-option>
              <a-option :value="0">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit">
                <template #icon><icon-search /></template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon><icon-refresh /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 操作按钮 -->
      <div class="flex mb-4" style="gap: var(--spacing-medium);">
        <a-button type="primary" @click="handleAdd">
          <template #icon><icon-plus /></template>
          新增角色
        </a-button>
        <a-button
          type="outline"
          status="danger"
          :disabled="!selectedKeys.length"
          @click="handleBatchDelete"
        >
          <template #icon><icon-delete /></template>
          批量删除
        </a-button>
      </div>

      <!-- 角色表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #roleType="{ record }">
          <a-tag :color="record.roleType === 1 ? 'blue' : 'green'">
            {{ record.roleType === 1 ? '系统角色' : '业务角色' }}
          </a-tag>
        </template>

        <template #status="{ record }">
          <a-switch
            v-model="record.status"
            :checked-value="1"
            :unchecked-value="0"
            @change="handleStatusChange(record)"
          />
        </template>

        <template #dataScope="{ record }">
          <span>{{ getDataScopeText(record.dataScope) }}</span>
        </template>

        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-button type="text" size="small" @click="handlePermission(record)">
              <template #icon><icon-settings /></template>
              分配权限
            </a-button>
            <a-popconfirm
              content="确定要删除这个角色吗？"
              @ok="handleDelete(record)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 角色表单弹窗 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="角色名称" field="roleName">
              <a-input v-model="formData.roleName" placeholder="请输入角色名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="角色编码" field="roleCode">
              <a-input v-model="formData.roleCode" placeholder="请输入角色编码" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="角色类型" field="roleType">
              <a-select v-model="formData.roleType" placeholder="请选择角色类型">
                <a-option :value="1">系统角色</a-option>
                <a-option :value="2">业务角色</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序" field="sort">
              <a-input-number v-model="formData.sort" placeholder="请输入排序" :min="0" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="数据权限" field="dataScope">
              <a-select v-model="formData.dataScope" placeholder="请选择数据权限">
                <a-option :value="1">全部数据权限</a-option>
                <a-option :value="2">自定数据权限</a-option>
                <a-option :value="3">本部门数据权限</a-option>
                <a-option :value="4">本部门及以下数据权限</a-option>
                <a-option :value="5">仅本人数据权限</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" field="status">
              <a-select v-model="formData.status" placeholder="请选择状态">
                <a-option :value="1">启用</a-option>
                <a-option :value="0">禁用</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="角色描述" field="description">
          <a-textarea
            v-model="formData.description"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formData.remark"
            placeholder="请输入备注"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 权限分配弹窗 -->
    <a-modal
      v-model:visible="permissionVisible"
      title="分配权限"
      width="800px"
      @ok="handlePermissionSubmit"
      @cancel="handlePermissionCancel"
    >
      <div class="permission-content">
        <a-tree
          ref="menuTreeRef"
          v-model:checked-keys="checkedMenuKeys"
          :data="menuTree"
          :checkable="true"
          :check-strictly="false"
          :default-expand-all="true"
          :field-names="{ key: 'id', title: 'menuName', children: 'children' }"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import type { TableColumnData } from '@arco-design/web-vue'

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleCode: '',
  status: undefined
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedKeys = ref<string[]>([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
  showTotal: true
})

// 表格配置
const columns: TableColumnData[] = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '角色名称', dataIndex: 'roleName', width: 150 },
  { title: '角色编码', dataIndex: 'roleCode', width: 150 },
  { title: '角色类型', slotName: 'roleType', width: 100 },
  { title: '数据权限', slotName: 'dataScope', width: 150 },
  { title: '排序', dataIndex: 'sort', width: 80 },
  { title: '状态', slotName: 'status', width: 80 },
  { title: '创建时间', dataIndex: 'createTime', width: 180 },
  { title: '操作', slotName: 'actions', width: 200, fixed: 'right' }
]

// 行选择配置
const rowSelection = reactive({
  type: 'checkbox' as const,
  showCheckedAll: true,
  onSelect: (rowKeys: string[]) => {
    selectedKeys.value = rowKeys
  },
  onSelectAll: (checked: boolean) => {
    if (checked) {
      selectedKeys.value = tableData.value.map((item: any) => item.id)
    } else {
      selectedKeys.value = []
    }
  }
})

// 表单相关
const formVisible = ref(false)
const formTitle = ref('')
const formRef = ref()
const formData = reactive({
  id: undefined,
  roleName: '',
  roleCode: '',
  description: '',
  roleType: 2,
  dataScope: 1,
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称' },
    { minLength: 2, message: '角色名称至少2个字符' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线' }
  ],
  roleType: [
    { required: true, message: '请选择角色类型' }
  ],
  dataScope: [
    { required: true, message: '请选择数据权限' }
  ]
}

// 权限分配相关
const permissionVisible = ref(false)
const menuTreeRef = ref()
const menuTree = ref([])
const checkedMenuKeys = ref<string[]>([])
const currentRole = ref<any>(null)

// 工具方法
const getDataScopeText = (dataScope: number) => {
  const texts = {
    1: '全部数据权限',
    2: '自定数据权限', 
    3: '本部门数据权限',
    4: '本部门及以下数据权限',
    5: '仅本人数据权限'
  }
  return texts[dataScope] || '未知'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    roleName: '',
    roleCode: '',
    status: undefined
  })
  handleSearch()
}

// 分页
const handlePageChange = (page: number) => {
  pagination.current = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  formTitle.value = '新增角色'
  resetForm()
  formVisible.value = true
}

// 编辑
const handleEdit = (record: any) => {
  formTitle.value = '编辑角色'
  Object.assign(formData, record)
  formVisible.value = true
}

// 删除
const handleDelete = async (record: any) => {
  try {
    // 调用删除API
    Message.success('删除成功')
    fetchData()
  } catch (error) {
    Message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedKeys.value.length} 个角色吗？`,
    onOk: async () => {
      try {
        // 调用批量删除API
        Message.success('删除成功')
        selectedKeys.value = []
        fetchData()
      } catch (error) {
        Message.error('删除失败')
      }
    }
  })
}

// 状态切换
const handleStatusChange = async (record: any) => {
  try {
    // 调用状态切换API
    Message.success(`${record.status ? '启用' : '禁用'}成功`)
  } catch (error) {
    // 恢复原状态
    record.status = record.status ? 0 : 1
    Message.error('操作失败')
  }
}

// 权限分配
const handlePermission = async (record: any) => {
  currentRole.value = record
  permissionVisible.value = true
  
  // 获取菜单树
  await fetchMenuTree()
  
  // 获取角色已有权限
  await fetchRoleMenus(record.id)
}

// 提交表单
const handleSubmit = async () => {
  const errors = await formRef.value?.validate()
  if (errors) return

  try {
    if (formData.id) {
      // 更新角色
      Message.success('更新成功')
    } else {
      // 新增角色
      Message.success('新增成功')
    }
    formVisible.value = false
    fetchData()
  } catch (error) {
    Message.error('操作失败')
  }
}

// 取消表单
const handleCancel = () => {
  formVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    roleName: '',
    roleCode: '',
    description: '',
    roleType: 2,
    dataScope: 1,
    sort: 0,
    status: 1,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 权限分配提交
const handlePermissionSubmit = async () => {
  try {
    const menuIds = menuTreeRef.value?.getCheckedKeys({ checkedStrategy: 'all' }) || []
    // 调用分配权限API
    Message.success('权限分配成功')
    permissionVisible.value = false
  } catch (error) {
    Message.error('权限分配失败')
  }
}

// 权限分配取消
const handlePermissionCancel = () => {
  permissionVisible.value = false
  checkedMenuKeys.value = []
  currentRole.value = null
}

// 获取菜单树
const fetchMenuTree = async () => {
  try {
    // 模拟菜单数据
    const mockMenus = [
      {
        id: 1,
        menuName: '系统管理',
        children: [
          { id: 11, menuName: '用户管理' },
          { id: 12, menuName: '角色管理' },
          { id: 13, menuName: '菜单管理' }
        ]
      },
      {
        id: 2,
        menuName: '系统监控',
        children: [
          { id: 21, menuName: '在线用户' },
          { id: 22, menuName: '操作日志' }
        ]
      }
    ]
    menuTree.value = mockMenus
  } catch (error) {
    Message.error('获取菜单失败')
  }
}

// 获取角色菜单权限
const fetchRoleMenus = async (roleId: string) => {
  try {
    // 模拟已分配的菜单
    checkedMenuKeys.value = ['11', '12']
  } catch (error) {
    Message.error('获取角色权限失败')
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        roleName: '超级管理员',
        roleCode: 'SUPER_ADMIN',
        description: '系统超级管理员',
        roleType: 1,
        dataScope: 1,
        sort: 0,
        status: 1,
        createTime: '2024-01-01 00:00:00'
      },
      {
        id: 2,
        roleName: '普通用户',
        roleCode: 'USER',
        description: '普通用户角色',
        roleType: 2,
        dataScope: 5,
        sort: 1,
        status: 1,
        createTime: '2024-01-01 00:00:00'
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    Message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
// 使用统一的设计系统，无需自定义样式
</style> 